import React, { useState, useEffect, useRef } from 'react';
import './TypeEffect.css';

const TypeEffect = ({
  text,
  speed = 30,
  startDelay = 0,
  showCursor = true,
  html = false,
  onTypingDone = () => {}
}) => {
  const [isDone, setIsDone] = useState(false)
  const contentRef = useRef(null)
  const timerRef = useRef(null)
  const currentIndexRef = useRef(0)
  const isTypingRef = useRef(false)
  const previousTextLengthRef = useRef(0)

  const updateCursorPosition = () => {
    const contentEl = contentRef.current
    if (!contentEl) return

    // 创建一个临时的 span 元素来测量文本宽度
    const tempSpan = document.createElement('span')
    tempSpan.style.visibility = 'hidden'
    tempSpan.style.position = 'absolute'
    tempSpan.style.whiteSpace = 'pre-wrap'
    tempSpan.style.font = window.getComputedStyle(contentEl).font
    tempSpan.textContent = contentEl.textContent || contentEl.innerHTML

    document.body.appendChild(tempSpan)
    const textWidth = tempSpan.getBoundingClientRect().width
    document.body.removeChild(tempSpan)

    // 更新光标位置
    setCursorStyle({ left: `${textWidth}px` })
  }

  const reset = () => {
    clearTimeout(timerRef.current)
    currentIndexRef.current = 0
    previousTextLengthRef.current = 0
    isTypingRef.current = false
    setIsDone(false)
    if (contentRef.current) {
      if (html) {
        contentRef.current.innerHTML = ''
      } else {
        contentRef.current.textContent = ''
      }
    }
    setCursorStyle({ left: '0px' })
  }

  const typeNextChar = () => {
    if (currentIndexRef.current >= text.length) {
      isTypingRef.current = false
      setIsDone(true)
      onTypingDone()
      return
    }

    currentIndexRef.current++
    const textToShow = text.substring(0, currentIndexRef.current)

    if (contentRef.current) {
      if (html) {
        contentRef.current.innerHTML = textToShow
      } else {
        contentRef.current.textContent = textToShow
      }
    }

    // 更新光标位置
    updateCursorPosition()

    timerRef.current = setTimeout(typeNextChar, speed)
  }

  const startTyping = () => {
    if (isTypingRef.current) return

    isTypingRef.current = true
    setIsDone(false)

    // 如果是从头开始，添加延迟；如果是继续打字，立即开始
    const delay = currentIndexRef.current === 0 ? startDelay : 0

    setTimeout(typeNextChar, delay)
  }

  useEffect(() => {
    // 检查是否有新内容添加
    if (text) {
      const oldText =
        previousTextLengthRef.current > 0 ? text.substring(0, previousTextLengthRef.current) : ''

      if (text !== oldText) {
        // 如果当前正在打字，先停止
        if (isTypingRef.current) {
          clearTimeout(timerRef.current)
          isTypingRef.current = false
        }

        // 保存之前文本的长度
        previousTextLengthRef.current = oldText.length

        // 如果之前已经完成了打字，重置 isDone 状态
        if (isDone) {
          setIsDone(false)
        }

        // 从新的起始位置开始打字
        currentIndexRef.current = previousTextLengthRef.current
        startTyping()
      }
    } else {
      // 如果文本被清空，重置组件
      reset()
    }

    return () => {
      clearTimeout(timerRef.current)
    }
  }, [text, isDone])

  return (
    <div className={`chatgpt-type-effect ${isDone ? 'is-done' : ''}`}>
      <div className="content-wrapper">
        <div className="content" ref={contentRef}></div>
        {showCursor && !isDone && <span className="cursor"></span>}
      </div>
    </div>
  );
};

export default TypeEffect;
